﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SIGCBI.Entities;
using System.Data;
using System.Data.Entity;
using System.Data.Objects;

namespace SIGCBI.Repository
{
    public interface IRolRepository
    {
        List<ROL> GetAllFromRol();
        List<ROL> GetAllFromRolByDescripcion(string criterio);
        ROL GetFromRolById(Int32 id);
        void AddRol(ROL rol);
        void UpdateRol(ROL rol);
        void DeleteRol(Int32 id);
        bool ExisteDuplicidad(string descripcion, Int32 id);
    }

    public class RolRepository : MasterDataAccess, IRolRepository
    {
        public List<ROL> GetAllFromRol()
        {
            var query = from c in Context.ROLs
                        select c;
            return query.ToList();
        }

        public List<ROL> GetAllFromRolByDescripcion(string criterio)
        {
            if (criterio != string.Empty)
            {
                var query = from c in Context.ROLs
                            where c.Descripcion.ToUpper().Contains(criterio.ToUpper())
                            select c;

                return query.ToList();
            }
            else
            {
                var query = from c in Context.ROLs
                            select c;

                return query.ToList();
            }
        }

        public ROL GetFromRolById(int id)
        {
            var query = from c in Context.ROLs
                        where c.ID.Equals(id)
                        select c;
            return query.SingleOrDefault();
        }

        public void AddRol(ROL rol)
        {
            Context.ROLs.Add(rol);
            Context.SaveChanges();
        }

        public void UpdateRol(ROL rol)
        {
            Context.Entry(rol).State = EntityState.Modified;
            Context.SaveChanges();
        }

        public void DeleteRol(int id)
        {
            var existe = Context.ROLs.Where(c => c.ID.Equals(id)).SingleOrDefault();
            if (existe != null)
            {
                Context.ROLs.Remove(existe);
                Context.SaveChanges();
            }
        }

        public bool ExisteDuplicidad(string descripcion, int id)
        {
            var query = from c in Context.ROLs
                        where c.Descripcion.ToUpper().CompareTo(descripcion.ToUpper()) == 0
                        && c.ID != id
                        select c;

            return query.Any();
        }
    }
}
